<template>
  <div
    v-loading="loading"
    style="max-height: 100%; overflow: auto"
    class="app-container calendar-list-container"
  >
    <div class="goodsinfo_box">
      <div class="goods-content">
        <el-form ref="goods" :rules="rules" :model="goods" label-width="100px">
          <div
            v-if="id === undefined"
            class="filter-container mar_bottom10"
          >
            <el-radio-group v-model="goods.type">
              <el-radio-button label="0">货品</el-radio-button>
              <el-radio-button label="1">组合装</el-radio-button>
            </el-radio-group>
          </div>
          <el-form-item
            v-if="id === undefined"
            label="货品编号："
            prop="goodsNo"
          >
            <el-input
              v-model="goods.goodsNo"
              style="width: 250px"
              placeholder="请输入商品编号"
            />
          </el-form-item>
          <el-form-item v-else label="货品编号：" prop="goodsNo">{{
            goods.goodsNo
          }}</el-form-item>
          <el-form-item label="货品名称：" prop="goodsName">
            <el-input v-model="goods.goodsName" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="是否上架：" prop="isOnSale">
            <el-switch
              v-model="goods.isOnSale"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>

          <el-form-item label="货品主图：" prop="picUrl">
            <UploadImage v-model="goods.picUrl" />
          </el-form-item>
          <el-form-item label="货品相册：" prop="gallery">
            <UploadImageList v-model="goods.gallery" :limit="20" />
          </el-form-item>

          <el-form-item
            v-if="goods.type == 0 && propertyList.length > 0"
            label="关联属性："
            prop="propertyIds"
          >
            <template>
              <el-checkbox-group
                v-model="goods.propertyIds"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="item in propertyList"
                  :key="item.id"
                  :label="item.id"
                >{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>

          <el-form-item label="货品简介：" prop="brief">
            <el-input
              v-model="goods.brief"
              type="textarea"
              rows="5"
              cols="20"
              maxlength="255"
              show-word-limit
              placeholder="请输入货品简介"
            />
          </el-form-item>
          <el-form-item
            v-if="goods.type == 0"
            label="货品管理："
            prop="salesCount"
          >
            <el-button type="" @click="addSingle">添加单品</el-button>
          </el-form-item>
          <el-form-item v-if="goods.type == 0" prop="brief">
            <el-table
              :data="goods.goodsItemPropertyList"
              render-header="labelHead"
              border
              size="small"
            >
              <el-table-column label="操作" align="center" width="120">
                <template slot-scope="scope">
                  <div class="operationBtn">
                    <el-tooltip
                      v-if="scope.row.id === undefined"
                      class="item mar_3"
                      effect="light"
                      content="删除"
                      placement="top"
                    >
                      <a @click="delhandleView(scope.row)">
                        <i class="el-icon-delete" />
                      </a>
                    </el-tooltip>

                    <el-tooltip
                      v-if="scope.row.id !== undefined"
                      class="item mar_3"
                      effect="light"
                      :content="scope.row.isEnabled ? '停用' : '启用'"
                      placement="top"
                    >
                      <a @click="setEnable(scope.row)">
                        <i
                          :class="
                            scope.row.isEnabled
                              ? 'el-icon-sold-out'
                              : 'el-icon-sell'
                          "
                        />
                      </a>
                    </el-tooltip>
                    <el-tooltip
                      class="item mar_3"
                      effect="light"
                      content="编辑"
                      placement="top"
                    >
                      <a @click="edithandleView(scope.row, scope.$index)">
                        <i class="el-icon-edit-outline" />
                      </a>
                    </el-tooltip>
                    <el-tooltip
                      class="item mar_3"
                      effect="light"
                      content="查看"
                      placement="top"
                    >
                      <a @click="showhandleView(scope.row)">
                        <i class="el-icon-view" />
                      </a>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="编码" align="center" width="100">
                <template slot-scope="scope">{{ scope.row.itemNo }}</template>
              </el-table-column>

              <el-table-column
                prop="picUrl"
                header-align="center"
                label="单品图片"
                width="100"
                align="center"
              >
                <template slot-scope="scope">
                  <viewer
                    :key="$downPath + scope.row.picUrl"
                    class="Centered"
                    :options="vieweroptions"
                  >
                    <img
                      v-if="scope.row.picUrl"
                      :key="$downPath + scope.row.picUrl"
                      class="avatar"
                      :src="$downPath + scope.row.picUrl"
                      width="40"
                    >
                  </viewer>
                </template>
              </el-table-column>

              <el-table-column
                v-for="item in header"
                :key="item.key"
                show-overflow-tooltip
                width="180px"
                header-align="center"
                :label="item.value"
              >
                <template slot-scope="scope">
                  <div
                    v-for="temp in scope.row.tempPropertyIds.filter(
                      (x) => x.key == item.key
                    )"
                    :key="temp.key"
                  >
                    {{ temp.optionValue }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="售价" header-align="center" align="right">
                <template slot-scope="scope">{{ scope.row.price }}</template>
              </el-table-column>
              <el-table-column label="库存" header-align="center" align="right">
                <template slot-scope="scope">{{ scope.row.stockNum }}</template>
              </el-table-column>
              <el-table-column label="是否启用" align="center">
                <template slot-scope="scope">{{
                  scope.row.isEnabled ? "启用" : "停用"
                }}</template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item v-if="goods.type == 1" label="售价：" prop="price">
            <el-input-number
              v-model="goods.price"
              class="el-input-numer-input"
              style="width: 200px"
              :controls="false"
              :min="0"
              :max="1000000"
              placeholder="请输入售价"
            />
          </el-form-item>
          <el-form-item label="详情：">
            <el-tabs v-model="activeName" type="border-card">
              <el-tab-pane label="商品详情" name="0">
                <editor
                  ref="detailEditor"
                  v-model="goods.detail"
                  style="margin-top: 10px"
                />
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dualog_bottom">
        <el-button @click="closeMain">取消</el-button>
        <el-button
          v-if="isEdit"
          type="primary"
          @click="handleEdit"
        >更新货品</el-button>
        <el-button v-else type="primary" @click="handlePublish">上架</el-button>
      </div>
    </div>
    <!--添加单品-->
    <el-dialog
      :title="currentStatus === 'update' ? '编辑' : '新建'"
      :visible.sync="singleGoodsVisible"
      :close-on-click-modal="false"
      width="800px"
      append-to-body
      @close="singleGoodsClose()"
    >
      <el-form
        ref="singleGoodsInfo"
        :model="singleGoodsInfo"
        status-icon
        label-position="right"
        label-width="150px"
        :rules="singleGoodsRules"
        style="width: fit-content; margin-left: 50px"
      >
        <el-form-item
          v-if="singleGoodsInfo.id === undefined"
          label="单品编码："
          prop="itemNo"
        >
          <el-input
            v-model="singleGoodsInfo.itemNo"
            style="width: 300px"
            maxlength="20"
            placeholder="单品编码"
          />
        </el-form-item>
        <el-form-item v-else label="单品编码：" prop="itemNo">{{
          singleGoodsInfo.itemNo
        }}</el-form-item>

        <el-form-item label="单品图片：" prop="picUrl">
          <UploadImage v-model="singleGoodsInfo.picUrl" />
        </el-form-item>

        <el-form-item label="单品简介：" prop="itemBrief">
          <el-input
            v-model="singleGoodsInfo.itemBrief"
            type="textarea"
            rows="5"
            cols="20"
            placeholder="请输入单品简介"
          />
        </el-form-item>

        <el-form-item label="售价：" prop="price">
          <el-input-number
            v-model="singleGoodsInfo.price"
            class="el-input-numer-input"
            style="width: 200px"
            :controls="false"
            :min="0"
            :max="1000000"
            placeholder="请输入售价"
          />
        </el-form-item>
        <el-form-item
          v-for="(item, index) in singleGoodsInfo.itemGoodsCheckList"
          :key="index"
          :prop="item.id + ''"
          :label="item.name + '：'"
        >
          <el-radio-group
            v-model="item.checkOptionsId"
            class="norm"
            @change="selectPropertyes($event, item)"
          >
            <el-radio
              v-for="item2 in item.optionsList"
              :key="item2.id"
              :label="item2.id"
              border
            >{{ item2.value }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否启用：" prop="isEnabled">
          <el-switch
            v-model="singleGoodsInfo.isEnabled"
            active-color="#13ce66"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="singleGoodsClose()">取消</el-button>
        <el-button
          v-if="currentStatus === 'add'"
          type="primary"
          @click="confirmSingleGoods('singleGoodsInfo')"
        >确定</el-button>
        <el-button
          v-else
          type="primary"
          @click="updateSingleGoods('singleGoodsInfo')"
        >确定</el-button>
      </span>
    </el-dialog>

    <!--查看单品-->
    <el-dialog
      title="查看单品详情"
      :visible.sync="showGoodsVisible"
      width="800px"
      append-to-body
      @close="closeWindow()"
    >
      <el-form
        ref="singleGoodsInfo"
        :model="singleGoodsInfo"
        status-icon
        label-position="right"
        label-width="150px"
        style="width: fit-content; margin-left: 50px"
      >
        <el-form-item label="单品编码：" prop="itemNo">
          {{ singleGoodsInfo.itemNo }}
        </el-form-item>

        <el-form-item label="单品图片：" prop="picUrl">
          <viewer
            :key="$downPath + singleGoodsInfo.picUrl"
            :options="vieweroptions"
          >
            <img
              v-if="singleGoodsInfo.picUrl"
              :key="$downPath + singleGoodsInfo.picUrl"
              class="avatar"
              :src="$downPath + singleGoodsInfo.picUrl"
              width="146"
            >
          </viewer>
        </el-form-item>

        <el-form-item label="售价：" prop="price">
          {{ singleGoodsInfo.price }}
        </el-form-item>

        <el-form-item label="单品简介：" prop="itemBrief">
          {{ singleGoodsInfo.itemBrief }}
        </el-form-item>

        <el-form-item
          v-for="(item, index) in singleGoodsInfo.itemGoodsCheckList"
          :key="index"
          :prop="item.id + ''"
          :label="item.name + '：'"
        >
          <span>{{ getCheckOptionName(item) }} </span>
        </el-form-item>

        <el-form-item label="是否启用：" prop="isReserve">
          <span>{{ singleGoodsInfo.isEnabled ? "是" : "否" }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  addGoods, getPropertyByCategory, queryByParamIds, getGoodsDetail, queryByItemId, editGoods, checkGoodsNo
} from '@/api/product'
import { setIsEnable, checkItemNo } from '@/api/goodsItems'
import Editor from '@/components/Tinymce'
import UploadImage from '@/components/UploadImage'
import UploadImageList from '@/components/UploadImageList'
export default {
  name: 'GoodsinfoForm',
  components: { Editor, UploadImage, UploadImageList },
  props: { id: undefined },
  data() {
    return {
      vieweroptions: { zIndex: 5000 },
      selIndex: 0,
      goodsNum: 1,
      singleGoodsRules: {
        itemNo: [
          { required: true, message: '单品编号不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在1~20个字符', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: this.goCheckItemNo }
        ],
        picUrl: [
          { required: true, message: '单品图片不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ]
      },
      rules: {
        goodsNo: [
          { required: true, message: '货品编号不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在1~20个字符', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: this.goCheckGoodsNo }
        ],
        picUrl: [
          { required: true, message: '货品主图不能为空', trigger: 'blur' }
        ],
        gallery: [
          { required: true, message: '货品相册不能为空', trigger: 'blur' }
        ],
        goodsName: [
          { required: true, message: '货品名称不能为空', trigger: 'blur' },
          { min: 1, max: 60, message: '长度在1~60个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ]
      },
      loading: false,
      currentIndex: undefined,
      currentStatus: '',
      showGoodsVisible: false,
      isSingleEdit: false,
      header: [],
      isEdit: false,
      goodsDetail: '',
      propertyList: [],
      haseCheckPropertyList: [],
      goods: {
        type: 0,
        id: undefined,
        goodsNo: undefined,
        picUrl: '',
        price: 0,
        goodsName: undefined,
        brief: undefined,
        itemBrief: undefined,
        isOnSale: true,
        onSaleTime: undefined,
        detail: undefined,
        salesCount: undefined,
        goodsItemPropertyList: [],
        propertyIds: []

      },
      singleGoodsInfo: {
        id: undefined,
        goodsNo: undefined,
        itemNo: undefined,
        isReserve: undefined,
        itemBrief: undefined,
        price: 0,
        picUrl: undefined,
        optionIds: [],
        tempPropertyIds: [],
        checkList: [],
        itemGoodsCheckList: [],
        isEnabled: true
      },

      goodsItemListForm: {
        goodsItemList: []
      },
      goodsList: [],
      specVisiable: false,
      singleGoodsVisible: false,
      activeName: '0'
    }
  },
  computed: {
    getCheckOptionName() {
      return function(pro) {
        var obj = pro.optionsList.filter(function(item, index, arr) {
          return item.id === pro.checkOptionsId
        })
        if (obj.length > 0) {
          return obj[0].value
        } else {
          return ''
        }
      }
    }
  },
  watch: {
    id() {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.activeName = '0'
      this.isEdit = false
      this.propertyList = []
      this.header = []
      this.haseCheckPropertyList = []
      this.goodsClean()
      this.goodsItemClean()
      this.getGoodsDetail()
      // 按照分类获取当前所有属性
      this.getPropertyList()
    },
    closeWindow() {
      this.showGoodsVisible = false
    },
    getGoodsDetail() {
      if (this.id !== undefined) {
        this.isEdit = true
        getGoodsDetail({ id: this.id }).then(res => {
          this.goods = res.data
          // 根据所选属性 设置表头
          this.handleCheckedCitiesChange(this.goods.propertyIds)
        })
      }
    },
    singleGoodsClose() {
      this.singleGoodsVisible = false
    },
    closeMain() {
      this.goodsClean()
      this.goodsItemClean()
      this.$emit('close')
    },
    edithandleView(row, goodsIndex) {
      this.currentIndex = goodsIndex
      this.singleGoodsInfo = Object.assign({}, row)
      this.currentStatus = 'update'
      this.isSingleEdit = true
      this.getGoodsOptions(row.id, row)
      this.singleGoodsVisible = true
      this.$nextTick(() => {
        this.$refs.singleGoodsInfo.clearValidate()
      })
    },

    validateSinglePropertyId(rule, value, callback) {
      const cc = this.singleGoodsInfo.itemGoodsCheckList.filter(x => x.id + '' === rule.field)
      if (cc === undefined || cc.length === 0) {
        callback(new Error('属性选项必须选择'))
      } else {
        if (cc[0].checkOptionsId === undefined) {
          callback(new Error('属性选项必须选择'))
        } else {
          callback()
        }
      }
    },
    addGoodsInfoRule() {
      this.singleGoodsInfo.itemGoodsCheckList.forEach(x => {
        this.singleGoodsRules[x.id + ''] = [{
          required: true, trigger: 'change', validator: this.validateSinglePropertyId
        }]
      })
    },

    setEnable(row) {
      var obj = {}
      Object.assign(obj, row)
      var msg = '停用'
      if (!obj.isEnabled) {
        msg = '启用'
        obj.isEnabled = true
      } else {
        obj.isEnabled = false
      }
      this.$confirm('确认' + msg + '该单品吗', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        setIsEnable(obj)
          .then(res => {
            var index = this.goods.goodsItemPropertyList.findIndex(x => x.id === obj.id)
            this.$set(this.goods.goodsItemPropertyList, index, obj)
            this.singleGoodsInfo.isEnabled = obj.isEnabled
            this.msg('处理成功')
          })
          .finally(res => {
            this.loading = false
          })
      })
    },

    showhandleView(row) {
      this.getGoodsOptions(row.id, row)
      this.showGoodsVisible = true
    },

    getGoodsOptions(itemId, row) {
      const self = this
      if (self.id !== undefined && itemId !== undefined) {
        self.singleGoodsInfo = Object.assign({}, row)
        self.singleGoodsInfo.id = itemId
        // 因为可以是有属性单品也可以是没有属性单品 因此以当前选中属性为标准
        var propertys = []
        self.haseCheckPropertyList.forEach(x => {
          propertys.push(x)
        })

        // 数据查询出来的已进行关联的属性
        queryByItemId({ itemNo: row.itemNo }).then(res => {
          // 构造单品可选属性
          // var propertys = []
          // res.data.forEach(x => {
          //   propertys.push(x.propertyId)
          // })
          queryByParamIds({ checkPropertyIds: propertys }).then(response => {
            var existId = res.data.filter(y => y.propertyOptionsId !== undefined && y.propertyOptionsId !== 0)
            if (self.singleGoodsInfo.itemGoodsCheckList === undefined || self.singleGoodsInfo.itemGoodsCheckList.length === 0) {
              self.$set(self.singleGoodsInfo, 'itemGoodsCheckList', response.data)
            }
            if (existId.length > 0) {
              // 如果之前选过 则设默认选中
              self.singleGoodsInfo.itemGoodsCheckList.forEach(x => {
                const obj = existId.filter(m => m.propertyId === x.id)
                if (obj.length > 0) {
                  self.$set(x, 'checkOptionsId', obj[0].propertyOptionsId)
                }
              })
            } else {
              // 之前未选属性 编辑后第二次编辑 此时已包含选中的值
            }
            self.addGoodsInfoRule()
          })
        })
      } else {
        // 原对象传入 不用处理
      }
    },

    labelHead(h, { column, index }) { // 动态表头渲染
      return h('span', { class: 'table-head', style: { width: '100%' }}, [column.label])
    },

    delhandleView(row) {
      if (row.id === undefined) {
        const index = this.goods.goodsItemPropertyList.indexOf(row)
        this.goods.goodsItemPropertyList.splice(index, 1)
      } else {
        this.$confirm('确认删除该条单品吗？', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const index = this.goods.goodsItemPropertyList.indexOf(row)
          this.goods.goodsItemPropertyList.splice(index, 1)
        })
      }
    },

    selectPropertyes(value, obj) {
      const self = this
      var key = ''
      var cvalue = value
      var cpropertyId = ''
      var coptionId = ''
      var optionValue = ''
      obj.optionsList.forEach(element => {
        if (value === obj.checkOptionsId) {
          key = 'KEY' + element.propertyId
          cpropertyId = element.propertyId
          coptionId = value
          if (value === element.id) {
            optionValue = element.value
          }
        }
      })

      var saveObj = { key: key, value: cvalue, propertyId: cpropertyId, optionId: coptionId, optionValue: optionValue }
      if (self.singleGoodsInfo.tempPropertyIds !== undefined) {
        if (self.singleGoodsInfo.tempPropertyIds.length > 0) {
          self.singleGoodsInfo.tempPropertyIds.forEach(x => {
            if (x.key === saveObj.key) {
              self.$set(x, 'key', saveObj.key)
              self.$set(x, 'optionId', saveObj.optionId)
              self.$set(x, 'value', saveObj.value)
              self.$set(x, 'propertyId', saveObj.propertyId)
              self.$set(x, 'optionValue', saveObj.optionValue)
              if ((self.singleGoodsInfo.id === undefined || self.isSingleEdit === false) && self.currentStatus === 'add') {
                if (this.tempPropertyIdsCheck(self.singleGoodsInfo.tempPropertyIds, x)) {
                  self.singleGoodsInfo.tempPropertyIds.push(x)
                }
              }
            } else {
              if ((self.singleGoodsInfo.id === undefined || self.isSingleEdit === false) && self.currentStatus === 'add') {
                if (this.tempPropertyIdsCheck(self.singleGoodsInfo.tempPropertyIds, saveObj)) {
                  self.singleGoodsInfo.tempPropertyIds.push(saveObj)
                }
              } else {
                if (this.tempPropertyIdsCheck(self.singleGoodsInfo.tempPropertyIds, saveObj)) {
                  self.singleGoodsInfo.tempPropertyIds.push(saveObj)
                }
              }
            }
          })
        } else {
          if ((self.singleGoodsInfo.id === undefined || self.isSingleEdit === false) && self.currentStatus === 'add') {
            if (this.tempPropertyIdsCheck(self.singleGoodsInfo.tempPropertyIds, saveObj)) {
              self.singleGoodsInfo.tempPropertyIds.push(saveObj)
            }
          } else {
            if (this.tempPropertyIdsCheck(self.singleGoodsInfo.tempPropertyIds, saveObj)) {
              self.singleGoodsInfo.tempPropertyIds.push(saveObj)
            }
          }
        }
      }
    },

    // 防重复
    tempPropertyIdsCheck(obj, item) {
      const cc = obj.filter(x => x.key === item.key)
      if (cc.length > 0) {
        return false
      }
      return true
    },

    // 查询分类关联属性
    getPropertyList() {
      getPropertyByCategory({}).then(res => {
        this.propertyList = res.data
      })
    },

    handleCheckedCitiesChange(value) {
      this.haseCheckPropertyList = value
      const property = { checkPropertyIds: this.haseCheckPropertyList }
      queryByParamIds(property).then(res => {
        this.header = []
        res.data.forEach(x => {
          const key = 'KEY' + x.id
          const value = x.name
          const obj = { key: key, value: value }
          this.header.push(obj)
        })
      })
    },

    goodsClean() {
      this.goods = {
        id: undefined,
        type: 0,
        price: 0,
        goodsNo: undefined,
        picUrl: undefined,
        gallery: [],
        goodsName: undefined,
        brief: undefined,
        isOnSale: true,
        onSaleTime: undefined,
        detail: undefined,
        salesCount: undefined,
        goodsItemPropertyList: [],
        propertyIds: []
      }
    },

    goodsItemClean() {
      this.singleGoodsInfo = {
        id: undefined,
        goodsNo: undefined,
        itemNo: undefined,
        price: 0,
        itemBrief: undefined,
        picUrl: undefined,
        optionIds: [],
        gallery: [],
        tempPropertyIds: [],
        checkList: [],
        itemGoodsCheckList: []
      }
    },

    // 添加单品
    addSingle() {
      this.currentStatus = 'add'
      this.singleGoodsVisible = true

      this.editSelectProperty()
      this.goodsItemClean()

      this.$nextTick(() => {
        this.$refs.singleGoodsInfo.clearValidate()
      })
    },

    // 生成选择后的属性列表
    editSelectProperty() {
      const self = this
      // 没有属性
      if (self.haseCheckPropertyList.length > 0) {
        var property = { checkPropertyIds: self.haseCheckPropertyList }
        queryByParamIds(property).then(res => {
          self.$set(self.singleGoodsInfo, 'itemGoodsCheckList', res.data)
          // 添加check属性
          self.addGoodsInfoRule()
          self.singleGoodsInfo.itemGoodsCheckList.forEach(x => {
            self.$set(x, 'checkOptionsId', undefined)
          })
        })
      }
    },

    dispImg: function(index) {
      this.selIndex = index
    },

    // 检查当前编码是否已使用
    goCheckItemNo(rule, value, callback) {
      checkItemNo({ id: this.singleGoodsInfo.id, itemNo: this.singleGoodsInfo.itemNo }).then(res => {
        if (res.data.length > 0) {
          callback(new Error('此编号已使用，请更换其他编号'))
        } else {
          const self = this
          if (self.goods.goodsItemPropertyList === undefined) {
            self.goods.goodsItemPropertyList = []
          }
          const cc = self.goods.goodsItemPropertyList.filter(x => x.itemNo === value)
          if (cc.length > 0 && cc[0].id !== self.singleGoodsInfo.id) {
            callback(new Error('此编号已使用，请更换其他编号'))
          } else {
            callback()
          }
        }
      })
    },

    // 检查当前货品编码是否已使用
    goCheckGoodsNo(rule, value, callback) {
      checkGoodsNo({ id: this.goods.id, goodsNo: value }).then(res => {
        if (res.data.length > 0) {
          callback(new Error('此编号已使用，请更换其他编号'))
        } else {
          callback()
        }
      })
    },

    // 添加到单品集合
    confirmSingleGoods(singleGoodsInfo) {
      const self = this
      self.$refs[singleGoodsInfo].validate(valid => {
        if (valid) {
          self.singleGoodsVisible = false
          // / 检查是否已添加过

          var cc = self.goods.goodsItemPropertyList.filter(x => x.itemNo === self.singleGoodsInfo.itemNo)
          if (cc.length < 1) {
            self.goods.goodsItemPropertyList.push(self.singleGoodsInfo)
          }
          self.goods.goodsItemPropertyList.forEach(x => {
            if (x.itemNo === self.singleGoodsInfo.itemNo) {
              self.$set(x, 'itemNo', self.singleGoodsInfo.itemNo)
              self.$set(x, 'stockNum', 0)
              self.$set(x, 'price', self.singleGoodsInfo.price)
              self.$set(x, 'picUrl', self.singleGoodsInfo.picUrl)
              self.$set(x, 'itemBrief', self.singleGoodsInfo.itemBrief)
              self.$set(x, 'optionIds', self.singleGoodsInfo.optionIds)
              self.$set(x, 'tempPropertyIds', self.singleGoodsInfo.tempPropertyIds)
              self.$set(x, 'checkList', self.singleGoodsInfo.checkList)
              self.$set(x, 'itemGoodsCheckList', self.singleGoodsInfo.itemGoodsCheckList)
            }
          })
        }
      })
    },
    // 单独更新单品
    updateSingleGoods(singleGoodsInfo) {
      const self = this
      self.$refs[singleGoodsInfo].validate(valid => {
        if (valid) {
          var err = ''
          if (self.singleGoodsInfo.itemGoodsCheckList === undefined) {
            err = '该单品还未选择商品属性，请选择'
          } else {
            self.singleGoodsInfo.itemGoodsCheckList.forEach(x => {
              if (x.checkOptionsId === undefined) {
                err = '属性必须设置相应值'
              }
            })
          }

          if (err !== '') {
            this.error(err)
            return
          }
          self.singleGoodsVisible = false
          // 变更属性
          self.$set(self.goods.goodsItemPropertyList, self.currentIndex, self.singleGoodsInfo)
        }
      })
    },
    handleChange(value) {
      console.log(value)
    },
    handleCancel: function() {
      this.id = undefined
      this.$emit('close')
    },
    handleEdit: function() {
      this.$refs['goods'].validate(valid => {
        if (valid) {
          var err = ''// 货品的场合
          if (this.goods.type === 0) {
            if (this.goods.goodsItemPropertyList.length < 1) {
              err = '至少添加一个单品'
            }
            // 多个单品时必须设定属性
            if (this.goods.propertyIds.length === 0 && this.goods.goodsItemPropertyList.length > 1) {
              err = '多个单品时货品必须设定关联属性'
            }
            //
            if (this.goods.propertyIds.length > 0 && this.goods.goodsItemPropertyList.length > 1) {
              this.goods.goodsItemPropertyList.forEach(x => {
                if (x.tempPropertyIds.length < this.goods.propertyIds.length) {
                  err = '单品属性选项必须选择'
                } else {
                  var chkFlg = false
                  this.goods.goodsItemPropertyList.forEach(y => {
                    if (x.itemNo !== y.itemNo) {
                      if (chkFlg) {
                        var propertyCount = y.tempPropertyIds.length
                        var i = 0
                        var stopFlg = false
                        while (!stopFlg && i < propertyCount) {
                          if (x.tempPropertyIds[i].optionId === y.tempPropertyIds[i].optionId) {
                            if (i === propertyCount - 1) {
                              err = '单品之间属性选择不能相同'
                            }
                          } else {
                            stopFlg = true
                          }
                          i++
                        }
                      }
                    } else {
                      chkFlg = true
                    }
                  })
                }
              })
            }
          }
          if (err !== '') {
            this.error(err)
            return
          }

          this.loading = true
          editGoods(this.goods).then(response => {
            this.loading = false
            this.msg('更新成功')
            this.singleGoodsInfo = {}
            this.$emit('fatherMethod')
            this.$emit('close')
          })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    handlePublish: function() {
      const self = this
      self.$refs['goods'].validate(valid => {
        if (valid) {
          var err = ''
          // 货品的场合
          if (self.goods.type === 0) {
            if (self.goods.goodsItemPropertyList.length < 1) {
              err = '至少添加一个单品'
            }
          }
          if (err !== '') {
            this.error(err)
            return
          }
          this.loading = false
          addGoods(this.goods)
            .then(res => {
              this.loading = false
              this.msg('创建成功')
              this.init()
              this.$emit('update:id', res.data.id)
              this.$emit('fatherMethod')
              this.$emit('close', 'add')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
<style  scoped>
.dualog_bottom {
  width: 100%;
  padding: 20px 0px 0px 0px;
  text-align: center;
}

.el-input-numer-input >>> .el-input__inner {
  text-align: left !important;
}

.delivery .el-form-item__error {
  width: 120px;
}
.norm.el-radio-button--medium .el-radio-button__inner {
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 0;
  margin-right: 10px;
  margin-bottom: 10px;
  border-left: 1px solid #dcdfe6;
}
.norm .el-radio.is-bordered {
  margin-left: 0px;
  margin-bottom: 10px;
  min-width: 100px;
}
.norm .el-radio.is-bordered + .el-radio.is-bordered {
  margin-left: 0px;
  margin-bottom: 10px;
}
</style>
